<template>
  <MyDialog
    :dialog-form="dialogForm"
    :dialog-visible="dialogVisible"
    @dialogClose="onClose"
    @dialogConfirm="onSubmit"
  >
    <template #dialogBox>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="115px"
        status-icon
      >
        <el-form-item label="人员姓名" prop="realName">
          <el-input
            v-model="ruleForm.realName"
            placeholder="输入人员姓名"
            maxlength="8"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="账号"
          v-if="bindType == 1"
          :prop="bindType == 2 ? '' : 'userAccount'"
        >
          <el-input
            v-model="ruleForm.userAccount"
            placeholder="输入账号"
            :disabled="props.row?.id"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          v-if="bindType == 2 && props.row?.id"
          prop="userTel"
        >
          <el-input v-model="ruleForm.userTel" placeholder="输入手机号" />
          <div style="font-size: 14px; color: gray">
            提示：手机号将用于接收各类消息推送，请填写常用手机号
          </div>
        </el-form-item>
        <el-form-item
          label="角色类型"
          prop="roleId"
          v-if="
            props.row?.roleId != '2c195fa2612b49f99647e4fe1962319a' &&
            props.row?.roleId != 'f65531c3ae374678a67b3bdacafb4537'
          "
        >
          <el-select v-model="ruleForm.roleId" placeholder="选择角色类型">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人类型" prop="directorTypes">
          <el-select
            v-model="ruleForm.directorTypes"
            multiple
            placeholder="选择负责人类型"
          >
            <el-option label="保养负责人" value="1" />
            <el-option label="验证负责人" value="2" />
            <el-option label="点检负责人" value="3" />
            <el-option label="维修负责人" value="4" />
            <el-option label="仓库负责人" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="positionId">
          <el-select
            v-model="ruleForm.positionId"
            @change="changePosition"
            placeholder="选择职位"
          >
            <el-option
              v-for="item in positionList"
              :key="item.id"
              :label="item.configValue"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门机构" prop="deptId">
          <el-cascader
            v-model="ruleForm.deptId"
            :props="cascadeProps"
            :options="deptList"
            placeholder="选择部门机构"
            filterable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
            v-model="ruleForm.entryDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择入职日期"
          />
        </el-form-item>
        <el-form-item label="账号状态" prop="enableState">
          <el-switch
            v-model="ruleForm.enableState"
            :active-value="1"
            :inactive-value="2"
            style="
              --el-switch-on-color: var(--el-color-primary);
              --el-switch-off-color: #fa4016;
            "
          />
        </el-form-item>
        <p class="tips">
          提示：默认密码为Admin@123 <a @click="copy">复制账号密码</a>
        </p>
      </el-form>
    </template>
  </MyDialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, defineAsyncComponent, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { validateTel, validateTel3 } from '/@/utils/toolsValidate'
import {
  getRoleList,
  postAny,
  getTree,
  postAddUser,
  putEditUser
} from '/@/api/setting/structure'
const MyDialog = defineAsyncComponent(
  () => import('/@/components/dialog/index.vue')
)
const ruleFormRef = ref<FormInstance>()
const bindType = JSON.parse(sessionStorage.getItem('shebei') as any).bindType

// 定义父组件传过来的值
const props = defineProps({
  myDialog: {
    type: Boolean,
    default: () => false
  },
  row: {
    type: Object,
    default: () => {}
  },
  curDept: {
    type: String,
    default: () => ''
  }
})
const emit = defineEmits(['flash'])

let [dialogVisible, roleList, positionList, deptList] = [
  ref<boolean>(false),
  ref<any>([]),
  ref<any>([]),
  ref<any>([])
] //弹窗是否出现
const dialogForm = reactive({
  width: '30%',
  title: '新增人员'
})
let ruleForm = reactive({
  realName: '',
  userAccount: '',
  userTel: '',
  sex: 1,
  roleId: '',
  deptId: '',
  positionId: '',
  positionName: '',
  entryDate: '',
  directorTypes: [],
  enableState: 1
})

const validateTel2 = (rule: any, value: any, callback: any) => {
  let reg2 =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/g
  if (value && !reg2.test(value)) {
    return callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  userTel: [{ validator: validateTel2, trigger: 'blur' }],
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { required: true, validator: validateTel, trigger: 'blur' }
  ],
  realName: [{ required: true, message: '输入姓名', trigger: 'blur' }],
  deptId: [{ required: true, message: '选择部门机构', trigger: 'change' }],
  roleId: [{ required: true, message: '选择角色类型', trigger: 'change' }]
})

const getRoles = async () => {
  let res = await getRoleList()
  if (res.code == 0) {
    roleList.value = res.data
  }
}

const getPosition = async () => {
  let res = await postAny({ configType: 'position_type' })
  if (res.code == 0) {
    positionList.value = res.data
  }
}

const cascadeProps = {
  value: 'id',
  label: 'deptName',
  children: 'children',
  emitPath: false,
  checkStrictly: true
}

const getDept = async () => {
  let res = await getTree()
  if (res.code == 0) {
    deptList.value = res.data
  }
}

const changePosition = (val: any) => {
  ruleForm.positionName = positionList.value.find((e: any) => {
    return e.id == ruleForm.positionId
  }).configValue
}

watch(
  () => props.myDialog,
  () => {
    getRoles()
    getPosition()
    getDept()
    if (JSON.stringify(props.row) == '{}') {
      dialogForm.title = '新增人员'
      let now = new Date()
      let year = now.getFullYear() // 得到年份
      let month = now.getMonth() // 得到月份
      let date = now.getDate() // 得到日期
      month = month + 1
      month = month.toString().padStart(2, '0')
      date = date.toString().padStart(2, '0')
      ruleForm.deptId = props.curDept
      ruleForm.roleId = ''
      var defaultDate = `${year}-${month}-${date}`
      Reflect.set(ruleForm, 'entryDate', defaultDate)
    } else {
      dialogForm.title = '编辑'
      nextTick(() => {
        ruleForm.realName = props.row.realName
        ruleForm.userTel = props.row.userTel
        ruleForm.sex = props.row.sex
        ruleForm.roleId = props.row.roleId
        ruleForm.deptId = props.row.deptId
        ruleForm.positionId = props.row.positionId
        ruleForm.positionName = props.row.positionName
        ruleForm.userAccount = props.row.userAccount
        ruleForm.entryDate = props.row.entryDate
        ruleForm.directorTypes =
          props.row.directorTypes != ''
            ? props.row.directorTypes.split(',')
            : []
        ruleForm.enableState = props.row.enableState
      })
    }
    dialogVisible.value = true
  }
)

const onClose = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
  dialogVisible.value = !dialogVisible.value
}

const onSubmit = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (JSON.stringify(props.row) == '{}') {
        let param = {
          realName: ruleForm.realName,
          userAccount: ruleForm.userAccount,
          sex: ruleForm.sex,
          roleId: ruleForm.roleId,
          deptId: ruleForm.deptId,
          positionId: ruleForm.positionId,
          positionName: ruleForm.positionName,
          entryDate: ruleForm.entryDate,
          directorTypes: ruleForm.directorTypes.join(','),
          enableState: ruleForm.enableState
        }
        let res = await postAddUser(param)
        if (res.code == 0) {
          ruleFormRef.value.resetFields()
          dialogVisible.value = !dialogVisible.value
          emit('flash')
          ElMessage.success('添加成功！')
        }
      } else {
        let param = {
          realName: ruleForm.realName,
          userAccount: ruleForm.userAccount,
          userTel: ruleForm.userTel,
          sex: ruleForm.sex,
          roleId: ruleForm.roleId,
          deptId: ruleForm.deptId,
          positionId: ruleForm.positionId,
          positionName: ruleForm.positionName,
          entryDate: ruleForm.entryDate,
          directorTypes: ruleForm.directorTypes.join(','),
          enableState: ruleForm.enableState,
          id: props.row.id
        }
        let res = await putEditUser(param)
        if (res.code == 0) {
          ruleFormRef.value?.resetFields()
          dialogVisible.value = !dialogVisible.value
          emit('flash')
          ElMessage.success('编辑成功！')
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const copy = () => {
  navigator.clipboard
    .writeText(`账号：${ruleForm.userAccount}；密码：Admin@123`)
    .then(
      function () {
        /* clipboard successfully set */
        ElMessage.success('复制成功！')
      },
      function () {
        /* clipboard write failed */
        ElMessage.error('你当前浏览器不支持复制呢！')
      }
    )
}
</script>

<style scoped lang="scss">
.el-select,
.el-date-picker {
  width: 100%;
}

.tips {
  margin-top: 10px;

  a {
    color: var(--el-color-primary);
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
